// 图表组件
const ChartComponents = {
    // 加载成绩趋势图
    loadGradeTrendChart: function(grades) {
        const ctx = document.getElementById('gradeTrendChart');
        if (!ctx) {
            console.error('找不到成绩趋势图容器');
            return;
        }

        // 按考试时间排序
        const sortedGrades = [...grades].sort((a, b) => new Date(a.examTime) - new Date(b.examTime));
        
        new Chart(ctx.getContext('2d'), {
            type: 'line',
            data: {
                labels: sortedGrades.map(grade => grade.examName),
                datasets: [{
                    label: '成绩',
                    data: sortedGrades.map(grade => grade.score),
                    borderColor: 'rgb(75, 192, 192)',
                    tension: 0.1,
                    fill: false
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: {
                        position: 'top',
                    },
                    tooltip: {
                        callbacks: {
                            label: function(context) {
                                return `成绩: ${context.raw}分`;
                            }
                        }
                    }
                },
                scales: {
                    y: {
                        beginAtZero: true,
                        max: 100,
                        title: {
                            display: true,
                            text: '分数'
                        }
                    },
                    x: {
                        title: {
                            display: true,
                            text: '考试'
                        }
                    }
                }
            }
        });
    },

    // 加载科目成绩分布图
    loadSubjectGradeChart: function(grades) {
        const ctx = document.getElementById('subjectGradeChart');
        if (!ctx) {
            console.error('找不到科目成绩分布图容器');
            return;
        }
        
        // 按科目分组统计
        const subjectGrades = {};
        grades.forEach(grade => {
            if (!subjectGrades[grade.subject]) {
                subjectGrades[grade.subject] = [];
            }
            subjectGrades[grade.subject].push(grade.score);
        });

        // 计算每个科目的平均分
        const subjects = Object.keys(subjectGrades);
        const averages = subjects.map(subject => {
            const scores = subjectGrades[subject];
            return scores.reduce((sum, score) => sum + score, 0) / scores.length;
        });

        new Chart(ctx.getContext('2d'), {
            type: 'bar',
            data: {
                labels: subjects,
                datasets: [{
                    label: '平均分',
                    data: averages,
                    backgroundColor: 'rgba(54, 162, 235, 0.5)',
                    borderColor: 'rgb(54, 162, 235)',
                    borderWidth: 1
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: {
                        position: 'top',
                    },
                    tooltip: {
                        callbacks: {
                            label: function(context) {
                                return `平均分: ${context.raw.toFixed(1)}分`;
                            }
                        }
                    }
                },
                scales: {
                    y: {
                        beginAtZero: true,
                        max: 100,
                        title: {
                            display: true,
                            text: '分数'
                        }
                    },
                    x: {
                        title: {
                            display: true,
                            text: '科目'
                        }
                    }
                }
            }
        });
    }
};

// 列表组件
const ListComponents = {
    // 加载最近考试列表
    loadRecentExamsList: async function(grades) {
        const tbody = document.getElementById('recentExamsTableBody');
        if (!tbody) {
            console.error('找不到最近考试列表容器');
            return;
        }

        tbody.innerHTML = '';

        if (!grades || grades.length === 0) {
            tbody.innerHTML = '<tr><td colspan="5" class="text-center">暂无考试记录</td></tr>';
            return;
        }

        try {
            // 获取所有考试的成绩排名
            const examRanks = await Promise.all(grades.map(async grade => {
                const allGrades = await fetchApi(`/grades/exam/${grade.examId}`);
                const sortedGrades = allGrades.sort((a, b) => b.score - a.score);
                const rank = sortedGrades.findIndex(g => g.studentId === grade.studentId) + 1;
                return { ...grade, rank };
            }));

            // 按考试时间排序
            const sortedGrades = examRanks.sort((a, b) => new Date(b.examTime) - new Date(a.examTime));

            // 显示最近5次考试
            const recentGrades = sortedGrades.slice(0, 5);
            
            recentGrades.forEach(grade => {
                const row = document.createElement('tr');
                row.innerHTML = `
                    <td>${grade.examName}</td>
                    <td>${grade.subject}</td>
                    <td>${formatStudentDateTime(grade.examTime)}</td>
                    <td><span class="badge badge-${grade.score >= 60 ? 'success' : 'danger'}">${grade.score}分</span></td>
                    <td>${grade.rank}</td>
                `;
                tbody.appendChild(row);
            });
        } catch (error) {
            console.error('加载最近考试列表失败:', error);
            tbody.innerHTML = '<tr><td colspan="5" class="text-center text-danger">加载失败，请稍后重试</td></tr>';
            showStudentToast('加载最近考试列表失败', 'danger');
        }
    }
};

// 卡片组件
const CardComponents = {
    // 更新最近考试信息
    updateRecentExamCard: function(grades) {
        const recentExamElement = document.getElementById('recentExam');
        if (!recentExamElement) {
            console.error('找不到最近考试卡片容器');
            return;
        }

        if (grades && grades.length > 0) {
            const latestGrade = grades[grades.length - 1];
            recentExamElement.innerHTML = `
                <small>${latestGrade.examName}</small><br>
                <small>成绩：${latestGrade.score}分</small>
            `;
        } else {
            recentExamElement.innerHTML = '<small>暂无考试记录</small>';
        }
    },

    // 更新成绩统计信息
    updateGradeStatsCard: function(grades) {
        const gradeStatsElement = document.getElementById('gradeStats');
        if (!gradeStatsElement) {
            console.error('找不到成绩统计卡片容器');
            return;
        }

        if (grades && grades.length > 0) {
            const avgScore = grades.reduce((sum, grade) => sum + grade.score, 0) / grades.length;
            const maxScore = Math.max(...grades.map(grade => grade.score));
            gradeStatsElement.innerHTML = `
                <small>平均分：${avgScore.toFixed(1)}分</small><br>
                <small>最高分：${maxScore}分</small>
            `;
        } else {
            gradeStatsElement.innerHTML = '<small>暂无成绩记录</small>';
        }
    }
};

// 导出组件
export { ChartComponents, ListComponents, CardComponents }; 